package com.zhc.tools.demo.service;

import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.zhc.tools.core.fileimport.domain.ImportFileResultEnum;
import com.zhc.tools.core.fileimport.domain.ImportLogObject;
import com.zhc.tools.core.fileimport.strategy.AbstractImportFileTemplate;
import com.zhc.tools.demo.domain.ImportOperateInfo;
import com.zhc.tools.core.fileimport.StrategyContext;

/**
 * 说明：
 * @author zhc
 */
@Service("importExampleStrategy")
public class ImportExampleStrategyService extends AbstractImportFileTemplate<ImportOperateInfo> {

	@Override
	protected boolean preDataFromFileDataMap(StrategyContext strategyContext) {
		// 数据内容
		for (Entry<Integer, Map<Integer, Object>> entry : strategyContext.getFileDataMap().entrySet()) {
			
//			if (entry.getKey().equals(0)) {
//				// 跳过标题行
//				continue;
//			}
			try {
				ImportLogObject importObject = strategyContext.createImportLogObject(entry);
				try {
					if (importObject != null) {
						Map<Integer, Object> dataMap = entry.getValue();
						this.logger.info(String.format("importExampleStrategy#preDataFromExcelDataMap line【%s】 dataMap【%s】", entry.getKey(), JSON.toJSONString(entry.getValue())));
						importObject.setData(dataMap);
					}
				} catch (Exception e) {
					importObject.setStatusByResultEnum(ImportFileResultEnum.CONV_PARAM_ERROR, e.getMessage());
					this.logger.error("importExampleStrategy#preDataFromExcelDataMap Exception :", e);
				}
			} catch (Exception e1) {
				this.logger.error("importExampleStrategy#preDataFromExcelDataMap createImportObject Exception :", e1);
			}
		}
		return true;
	}

	@Override
	protected boolean preExecuteData(StrategyContext strategyContext) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean executeImport(StrategyContext strategyContext) {
		int success = 0;
		for (ImportLogObject importObject : strategyContext.getExecuteDataList()) {
			boolean result = true;
			this.logger.info(String.format("importExampleStrategy#executeImport line【%s】 dataMap【%s】", importObject.getExcelNo(), JSON.toJSONString(importObject.getData())));
			if (result) {
				importObject.setStatusByResultEnum(ImportFileResultEnum.SUCCESS, null);
				success++;
			} else {
				importObject.setStatusByResultEnum(ImportFileResultEnum.BUSINESS_PARAM_ERROR, null);
			}
		}
		strategyContext.setSuccessCount(success);
		return true;
	}
}
